package com.mojo.jedis.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.Lock;

/**
 * redis分布式锁
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2023, 广州九尾信息科技有限公司
 * @date 2023/3/8 16:12
 */
@Service
public class RedisLockService {
    private static final Logger logger = LoggerFactory.getLogger(RedisLockService.class);
    @Autowired
    private RedisLockRegistry redisLockRegistry;

    public void lock(String key) {
        Lock lock = obtainLock(key);
        lock.lock();
    }

    public void unlock(String key) {
        Lock lock = obtainLock(key);
        try {
            lock.unlock();
            redisLockRegistry.expireUnusedOlderThan(5000L);
        } catch (Exception e) {
            logger.error("分布式锁【{}】释放异常", lock, e);
            throw new RuntimeException(e);
        }
    }

    private Lock obtainLock(String lockKey) {
        return redisLockRegistry.obtain(lockKey);
    }
}
